<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Mp;
use App\Models\Order;
use App\Models\Recharge;
use App\Models\User;
use App\Services\wxService;
use EasyWeChat\Pay\Message;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Symfony\Component\Console\Helper\Helper;

class RechargeController extends Controller
{

    protected $user;
    public function __construct()
    {
        $this->user = Auth::guard('api')->user();
        $this->middleware('auth:api', ['except' => ['index', 'wxNotfiyUrl']]);
    }
    //充值列表
    public function index(Request $request, Recharge $recharge)
    {
        $query = $recharge->newQuery();
        if (!$request->has('type') || !in_array($request->type, [0, 1])) {
            return $this->error('类型错误');
        }
        $list = $query->where('status', 1)->where('type', $request->type)->select('id', 'name', 'price', 'donate', 'integral', 'desc', 'tuijian', 'vip_day')->get()->toArray();
        return $this->success('success',$list);
   }

    public function pay(Request $request)
    {
        DB::beginTransaction();
        try {
            if (!$request->has('mp') || !is_numeric($request->mp)) {
                return $this->error('mp配置错误');
            }
            if (!$request->has('shopid') || !is_numeric($request->shopid)) {
                return $this->error('商品id错误');
            }
            $shop = Recharge::find($request->shopid);
            if (empty($shop)) {
                return $this->error('商品不存在');
            }
            $orderid = genRequestSn(12);
            //生成订单
            $order = new Order();
            $order->user_id = $this->user->id;
            $order->orderid = $orderid;
            $order->shop_id = $request->shopid;
            $order->type = 1;
            $order->status = 0;
            $price = $shop->price;
            $order->mps_id = $this->user->mps_id;
            $order->price = $price;
            $order->access_status = 0;
            $res = $order->save();
            $wx = new wxService('miniapppay', $request->mp);
            $app = $wx->run();
            $wxconfig = $app->getConfig();
            $config = [
                "mchid" => $wxconfig['mch_id'], // <---- 请修改为您的商户号
                "out_trade_no" => $orderid,
                "appid" => $wxconfig['app_id'], // <---- 请修改为服务号的 appid
                "description" => "购买视频",
                "notify_url" => $wxconfig['mpconfig']->notfiy_url . '/' . $wxconfig['mch_id'],
                "attach" => json_encode(['mp' => $request->mp]),
                "amount" => [
                    "total" => (int)($price * 100),
                    "currency" => "CNY"
                ],
                "payer" => [
                    "openid" => $this->user->wx_openid // <---- 请修改为服务号下单用户的 openid
                ]
            ];
            $response = $app->getClient()->postJson("v3/pay/transactions/jsapi", $config);
            Log::info('获取支付信息', $response->toArray(false));
            $prepayId = $response->toArray(false)['prepay_id'];
            $utils = $app->getUtils();
            $appId = $wxconfig['app_id'];
            $signType = 'RSA'; // 默认RSA，v2要传MD5
            $config = $utils->buildMiniAppConfig($prepayId, $appId, $signType); // 返回数组
            if ($res && !empty($config)) {
                DB::commit();
                return $this->success('success', $config);
            } else {
                DB::rollBack();
                return $this->error('发生错误');
            }
        } catch (\Exception $exception) {
            DB::rollBack();
            Log::error('支付错误', ['hang' => $exception->getLine(), 'code' => $exception->getCode(), 'msg' => $exception->getMessage(), 'file' => $exception->getFile()]);
            return $this->error('发生错误请联系维护人员');

        }
   }

    public function wxNotfiyUrl(Request $request, $mchid = '')
    {
        $reqdata = $request->all();
        Log::info('支付回调数据', [$mchid, $reqdata, $request->input()]);
        if (empty($mchid) || !is_numeric($mchid)) {
            Log::channel('pay')->error('商户信息获取异常', [$mchid]);
            return $this->error('err');
        }
        $mchinfo = Mp::where('mch_id', $mchid)->where('status', 1)->first();
        if (empty($mchinfo)) {
            Log::channel('pay')->error('商户信息获取失败', [$mchid, $mchinfo]);
            return $this->error('err');
        }
        $wx = new wxService('miniapppay', $mchinfo->id);
        $app = $wx->run();
        $server = $app->getServer();
        $server->handlePaid(function (Message $message, \Closure $next) {
            try {
                DB::beginTransaction();
                $order = Order::where(['orderid' => $message->out_trade_no, 'status' => 0, 'access_status' => 0])->first();
                $shop = Recharge::find($order->shop_id);
                if ($shop->type == 1) {
                    User::where('id', $order->user_id)->update(['vip_end_time' => strtotime(Carbon::now()->addDays($shop->vip_day)->toDateTimeString())]);
                } else {
                    if (User::integral($order->user_id, $shop->integral, '购买爽豆', 'BUY_INTEGRAL')) {
                        $order->access_status = 1;
                    }
                }
                $order->status = 1;
                if ($order->save()) {
                    DB::commit();
                    return $next($message);
                } else {
                    DB::rollBack();
                    Log::channel('pay')->error('微信支付回调处理异常-保持失败');
                    return 'error';
                }
            } catch (\Exception $exception) {
                DB::rollBack();
                Log::channel('pay')->error('微信支付回调处理异常', ['hang' => $exception->getLine(), 'code' => $exception->getCode(), 'msg' => $exception->getMessage(), 'file' => $exception->getFile()]);
            }
        });
        return $server->serve();

    }
}
